<template>
  <div class="publish-post">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>发布新帖子</span>
          <el-button @click="goBack" type="text">返回列表</el-button>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="postForm" 
        :rules="rules" 
        label-position="top"
        v-loading="loading"
      >
        <el-form-item label="帖子标题" prop="title">
          <el-input 
            v-model="postForm.title" 
            placeholder="请输入帖子标题（5-50个字符）" 
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="帖子分类" prop="category">
          <el-select 
            v-model="postForm.category" 
            placeholder="请选择帖子分类"
            style="width: 100%;"
          >
            <el-option 
              v-for="item in categories" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="帖子内容" prop="content">
          <el-input 
            v-model="postForm.content" 
            type="textarea" 
            placeholder="请输入帖子内容（10-2000个字符）"
            :rows="10"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>
        
        <div class="form-actions">
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="submitForm" :disabled="loading">发布帖子</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { useApartmentUserStoreHook } from "@/store/modules/apartmentUser";
import postsApi, { type CreatePostDto } from '@/api/posts';

const router = useRouter();
const formRef = ref<FormInstance>();
const loading = ref(false);
const apartmentUserStore = useApartmentUserStoreHook();

// 帖子表单
const postForm = reactive<CreatePostDto>({
  title: '',
  content: '',
  category: '',
  authorId: apartmentUserStore.userId // 从 Pinia 中获取用户 ID
});

// 分类选项
const categories = [
  { value: 'apartment', label: '公寓信息' },
  { value: 'roommate', label: '室友寻找' },
  { value: 'experience', label: '居住体验' },
  { value: 'question', label: '问题咨询' },
  { value: 'other', label: '其他' },
];

// 表单验证规则
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入帖子标题', trigger: 'blur' },
    { min: 5, max: 50, message: '标题长度应在 5 到 50 个字符之间', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择帖子分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入帖子内容', trigger: 'blur' },
    { min: 10, max: 2000, message: '内容长度应在 10 到 2000 个字符之间', trigger: 'blur' }
  ]
});

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid, fields) => {
    if (!valid) {
      console.log('表单验证失败:', fields);
      return;
    }
    
    try {
      loading.value = true;
      
      // 检查用户 ID 是否存在
      if (!apartmentUserStore.userId) {
        ElMessage.error('用户未登录或无法获取用户ID，请重新登录');
        return;
      }
      
      console.log('正在提交帖子数据:', {
        title: postForm.title,
        content: postForm.content,
        category: postForm.category,
        authorId: apartmentUserStore.userId
      });
      
      // 调用创建帖子 API
      await postsApi.createPost({
        title: postForm.title,
        content: postForm.content,
        category: postForm.category,
        authorId: apartmentUserStore.userId
      });
      
      ElMessage.success('帖子发布成功！');
      router.push('/posts/main');
    } catch (error) {
      console.error('发布帖子失败:', error);
      
      // 提供更具体的错误信息
      let errorMessage = '发布帖子失败，请稍后重试';
      if (error.response && error.response.data && error.response.data.message) {
        errorMessage = `发布失败: ${error.response.data.message}`;
      }
      
      ElMessage.error(errorMessage);
    } finally {
      loading.value = false;
    }
  });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 返回列表
const goBack = () => {
  router.push('/posts/main');
};
</script>

<style scoped>
.publish-post {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  gap: 12px;
}

:deep(.el-textarea__inner) {
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
  line-height: 1.6;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>
